import APIS from '@/apis';
import URLS from '@/apis/APIUrlDefine';
import Const from '@/common/Const';
import request from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import { Upload, Button } from 'antd';

import { RcCustomRequestOptions } from 'antd/lib/upload/interface';
import React, { useState } from 'react';
import './index.css';

const DocumentUpload: React.FC<any> = (props) => {
    const [showAddButton, updateAddButton] = useState(props.preDoc ? false : true);
    const [fileList, updateFileList] = props.preDoc
        ? useState<any>([
            {
                uid: Date.now(),
                percent: 100,
                url: URLS.SERVER_PICTURE_URL + props.preDoc,
                status: 'done',
            },
        ])
        : useState<any>([]);

    //自定义上传方法
    const customRequestUpload = async (option: RcCustomRequestOptions) => {
        var data = new FormData();
        updateFileList([
            {
                uid: option.file.uid,
                percent: 99,
                status: 'uploading',
            },
        ]);
        data.append('filename', option.file);
        data.append('type', '3');
        var result = await request('/api/utils/v1/upload', {
            method: 'POST',
            data: data,
        }).catch((ex) => { });
        if (result) {
            var asset = await APIS.AssetAPI.CreateNewAsset({
                url: result.data,
                type: Const.ASSET_TYPE.DOCUMENT_TYPE,
            }).catch(() => { });
            updateFileList([
                {
                    uid: option.file.uid,
                    percent: 100,
                    url: URLS.SERVER_PICTURE_URL + asset.data?.url,
                    status: asset.data ? 'done' : "error",
                },
            ]);
            props.handleDocChange?.(result.data);
        }
    };

    return (
        <div style={{ display: 'flex' }}>
            <Upload
                accept='.doc,.docx'
                className="uplaod-image-btn"
                showUploadList={{ showPreviewIcon: true, showRemoveIcon: true }}
                multiple={false}
                name="logo"
                action="/upload.do"
                onRemove={() => { }}
                fileList={fileList}
                customRequest={customRequestUpload}
                onChange={({ fileList }) => {
                    updateAddButton(fileList.length === 0);
                    updateFileList(fileList);
                }}
                listType="picture-card"
            >
                {showAddButton ? <Button icon={<PlusOutlined />}></Button> : null}
            </Upload>
        </div>
    );
};

export default DocumentUpload;
